package com.example.service;

import com.example.entity.Driver;
import com.example.entity.DriverStatus;
import com.example.entity.Vehicle;
import com.example.entity.VehicleStatus;
import com.example.repository.DriverRepository;
import com.example.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DriverService {
    private final DriverRepository driverRepository;
    private final VehicleRepository vehicleRepository;

    @Autowired
    public DriverService(DriverRepository driverRepository, VehicleRepository vehicleRepository) {
        this.driverRepository = driverRepository;
        this.vehicleRepository = vehicleRepository;
    }

    public String applyForJoining(Driver driver, Vehicle vehicle) {
        // 检查 license_number 是否重复
        if (driverRepository.existsById(driver.getLicenseNumber())) {
            return "该驾驶证及司机已经添加！";
        }
        
        // 如果是公司提供车辆，需要检查并分配可用车辆
        if (vehicle.isCompanyOwned() && vehicle.getLicensePlate().startsWith("CP")) {
            // 查找可用的公司车辆
            List<Vehicle> availableCompanyVehicles = vehicleRepository.findByCompanyOwnedTrueAndStatus(VehicleStatus.unassigned);
            
            if (availableCompanyVehicles.isEmpty()) {
                return "当前没有可用的公司车辆，无法完成加盟申请！";
            }
            
            // 分配第一辆可用的公司车辆
            Vehicle companyVehicle = availableCompanyVehicles.get(0);
            driver.setVehicle(companyVehicle);
            
            // 将车辆设置为已分配状态
            companyVehicle.setStatus(VehicleStatus.assigned);
            vehicleRepository.save(companyVehicle);
            
            // 保存司机信息
            driver.setStatus(DriverStatus.APPROVED);
            driverRepository.save(driver);
            
            return "司机加盟申请已通过，已为您分配公司车辆：" + companyVehicle.getLicensePlate();
        } else {
            // 司机自带车辆或自动驾驶车辆的处理逻辑
            // 检查车牌是否重复
            if (vehicleRepository.existsById(vehicle.getLicensePlate())) {
                return "该车牌已被使用！";
            }
            
            // 直接通过加盟申请，设置状态为 APPROVED
            driver.setStatus(DriverStatus.APPROVED);
            vehicle.setStatus(VehicleStatus.AVAILABLE);
            vehicleRepository.save(vehicle);
            driverRepository.save(driver);
            return "司机加盟申请已通过，车辆信息已同步。";
        }
    }
    
    public List<Driver> getAllDrivers() {
        // 添加日志输出，检查返回的司机列表是否为空
        List<Driver> drivers = driverRepository.findAll();
        System.out.println("查询到的司机数量：" + drivers.size());
        return drivers;
    }
}
